/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.utils;

import org.tianyun.cloud.common.dto.PageResult;

import java.util.List;

/**
 * PageBuilder
 *
 * @auther ebert_chan
 */
public class PageBuilder<T> {

    // 第N页，从1开始
    private int pageIndex;

    // 每页显示记录数，默认10条
    private int pageSize;

    // 总记录数
    private long totals;

    // 结果集列表
    private List<T> result;

    public PageBuilder() {
    }

    public PageBuilder(int pageIndex, int pageSize) {
        this();
        this.setPage(pageIndex, pageSize);
    }

    private PageBuilder<T> setPage(int pageIndex, int pageSize) {
        this.pageIndex = Math.max(1, pageIndex);
        this.pageSize = Math.max(1, pageSize);
        return this;
    }

    public PageBuilder<T> setTotals(long totals) {
        this.totals = Math.max(0, totals);
        return this;
    }

    public PageBuilder<T> setResult(List<T> result) {
        this.result = result;
        return this;
    }

    private void calculate(PageResult<T> pageResult) {
        if (pageResult.getTotals() <= 0 || pageResult.getPageSize() <= 0) {
            pageResult.setPages(0);
        } else {
            pageResult.setPages((pageResult.getTotals() / pageResult.getPageSize()) + (pageResult.getTotals() % pageResult.getPageSize() != 0 ? 1 : 0));
        }
    }

    public int getPageIndex() {
        return pageIndex;
    }

    public int getPageSize() {
        return pageSize;
    }

    public long getTotals() {
        return totals;
    }

    public PageResult<T> build() {
        PageResult<T> pageResult = new PageResult<T>();
        pageResult.setPageIndex(pageIndex);
        pageResult.setPageSize(pageSize);
        pageResult.setTotals(totals);
        pageResult.setResult(result);
        this.calculate(pageResult);
        return pageResult;
    }

}
